package test;

import entity.Person;

import java.lang.reflect.Field;

public class AccessPersonFields {
    public static void main(String[] args) {
        try {
            // 通过反射加载一个Person实例
            Class cls = Class.forName("entity.Person");
            Object person = cls.newInstance();
            // 获取private String name 属性
            Field name = cls.getDeclaredField("name");
            // name属性为private ，这里已超出其访问范围，不能直接访问
            // 通过setAccessible(true);
            name.setAccessible(true);
            // 先取值看一下
            System.out.println("赋值前的name:"+name.get(person));
            // 为name属性赋值
            name.set(person,"New Person");
            //展示一下赋值效果

            System.out.println("赋值后的name:"+name.get(person));
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        } finally {
        }
    }
}
